package com.example.state.machine.config;

import com.example.state.machine.enums.PaymentEvent;
import com.example.state.machine.enums.PaymentState;
import org.springframework.context.annotation.Configuration;
import org.springframework.statemachine.config.EnableStateMachineFactory;
import org.springframework.statemachine.config.EnumStateMachineConfigurerAdapter;
import org.springframework.statemachine.config.builders.StateMachineStateConfigurer;
import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer;

import java.util.EnumSet;

/*
 * 支付状态机配置
 */
@Configuration
@EnableStateMachineFactory
public class PaymentStateMachineConfig extends EnumStateMachineConfigurerAdapter<PaymentState, PaymentEvent> {

    @Override
    public void configure(StateMachineStateConfigurer<PaymentState, PaymentEvent> states) throws Exception {
        states
                .withStates()
                .initial(PaymentState.INITIALIZED)
                .states(EnumSet.allOf(PaymentState.class));
    }

    @Override
    public void configure(StateMachineTransitionConfigurer<PaymentState, PaymentEvent> transitions) throws Exception {
        transitions
                // 开始支付：INITIALIZED → PROCESSING
                .withExternal()
                .source(PaymentState.INITIALIZED).target(PaymentState.PROCESSING)
                .event(PaymentEvent.START_PAY)
                .and()

                // 支付成功：PROCESSING → SUCCEEDED
                .withExternal()
                .source(PaymentState.PROCESSING).target(PaymentState.SUCCEEDED)
                .event(PaymentEvent.PAY_SUCCESS)
                .and()

                // 支付失败：PROCESSING → FAILED
                .withExternal()
                .source(PaymentState.PROCESSING).target(PaymentState.FAILED)
                .event(PaymentEvent.PAY_FAIL);
    }
}